﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Task = System.Threading.Tasks.Task;

namespace Agile.VSIX {
    /// <summary>
    /// 清理所有文档
    /// </summary>
    internal sealed class CleanupAllCodeCommand {
        /// <summary>
        /// Command ID.
        /// </summary>
        public const int CommandId = 4135;

        /// <summary>
        /// Command menu group (command set GUID).
        /// </summary>
        public static readonly Guid CommandSet = new Guid("1c21120b-12b7-4d3a-ab61-1962f6426c0c");

        /// <summary>
        /// VS Package that provides this command, not null.
        /// </summary>
        private readonly AsyncPackage package;
        /// <summary>
        /// Initializes a new instance of the <see cref="CleanupAllCodeCommand"/> class.
        /// Adds our command handlers for menu (commands must exist in the command table file)
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        /// <param name="commandService">Command service to add command to, not null.</param>
        private CleanupAllCodeCommand(AsyncPackage package,OleMenuCommandService commandService) {
            this.package = package ?? throw new ArgumentNullException(nameof(package));
            commandService = commandService ?? throw new ArgumentNullException(nameof(commandService));

            var menuCommandID = new CommandID(CommandSet,CommandId);
            var menuItem = new MenuCommand(this.Execute,menuCommandID);
            commandService.AddCommand(menuItem);
        }

        /// <summary>
        /// Gets the instance of the command.
        /// </summary>
        public static CleanupAllCodeCommand Instance {
            get;
            private set;
        }

        /// <summary>
        /// Gets the service provider from the owner package.
        /// </summary>
        private Microsoft.VisualStudio.Shell.IAsyncServiceProvider ServiceProvider {
            get {
                return this.package;
            }
        }

        /// <summary>
        /// Initializes the singleton instance of the command.
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        public static async Task InitializeAsync(AsyncPackage package) {
            // Switch to the main thread - the call to AddCommand in CleanupAllCodeCommand's constructor requires
            // the UI thread.
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(package.DisposalToken);

            OleMenuCommandService commandService = await package.GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;
            Instance = new CleanupAllCodeCommand(package,commandService);
        }

        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void Execute(object sender,EventArgs e) {
            ThreadHelper.ThrowIfNotOnUIThread();

            DTE dte = ServiceProvider.GetServiceAsync(typeof(DTE)).Result as DTE;

            IEnumerable<ProjectItem> AllProjectItems = SolutionHelper.GetAllItemsInSolution<ProjectItem>(dte.Solution).
               Where(x => CodeCleanupAvailabilityLogic.CanCleanupProjectItem(x));

            foreach(var projectItem in AllProjectItems) {
                var projectItemFileName = projectItem.GetFileName();
                bool wasOpen = projectItem.IsOpen[EnvDTE.Constants.vsViewKindTextView] || projectItem.IsOpen[EnvDTE.Constants.vsViewKindCode];
                if(!wasOpen) {
                    try {
                        projectItem.Open(EnvDTE.Constants.vsViewKindTextView);
                    } catch(Exception) {
                       
                    }
                }
                if(projectItem.Document != null) {
                    CodeCleanupManager.Cleanup(projectItem.Document.GetTextDocument());
                    if(!wasOpen) {
                        projectItem.Document.Close(vsSaveChanges.vsSaveChangesYes);
                    }
                }
                OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupAvailabilityLogic.CanCleanupProjectItem returned false for '{projectItemFileName}' due to the project item not being a physical file.");
            }


        }
    }
}
